<template>
  <div class="report-export-button">
    <el-button
      :loading="defaultLoading?loading:defaultLoading"
      type="text"
      size="small"
      class="report-export"
      data-tooltip="导出"
      @click="beforeExport">
      导出数据
      <img :src="templateImg || exportImg" :style="{width: width + 'px', height: height + 'px'}" alt="导出订单">
    </el-button>
  </div>
</template>
<script>
import axios from 'axios';
import { standardFormatTime } from '@/filters/date';
import store from '../../store';
import { getToken } from '@/utils/auth';
import exportImg from '@/assets/reportManage/export.png';

const {
  BASE_API
} = process.env;

export default {
  name: 'ExportButton',
  props: {

    btnText: { // 导出的api
      type: String,
      default: '确定'
    },
    mediumBtnStyle: { // 导出传入的参数
      type: Object,
      default: () => {
        return {};
      }
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isMeidum: {
      type: Boolean,
      default: false
    },
    queryData: { // 导出传入的参数
      type: Object,
      default: () => {
        return {};
      }
    },
    exportApi: { // 导出的api
      type: String,
      default: () => {
        return '';
      }
    },
    exportName: { // 导出文件的名字
      type: String,
      default: () => {
        return '';
      }
    },
    templateImg: { // 导出模板的img
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 16
    },
    height: {
      type: Number,
      default: 16
    },
    tooltipContent: {
      type: String,
      default: '导出'
    },
    defaultLoading: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      exportImg,
      loading: false,
      cancelAxios: null
    };
  },
  methods: {
    // 设置token
    serviceToken(service) {
      // request拦截器
      service.interceptors.request.use(
        config => {
          const token = store.getters.token || getToken();
          if (token) {
            config.headers.common['token'] = token;
          }
          return config;
        },
        error => {
          console.log(error);
          Promise.reject(error);
        }
      );
    },
    beforeExport() {
      if (this.isMeidum) {
        this.$emit('beforeExport');
      } else {
        this.btnExport();
      }
    },
    btnExport(params = null) {
      this.loading = true;
      var source = axios.CancelToken.source();
      const service = axios.create({
        baseURL: BASE_API, // api 的 base_url
        timeout: 1800000, // 请求超时时间
        headers: {
          'Content-Type': 'application/octet-stream',
          'Content-Disposition': 'attachment;filename=kpi.xlsx'
        },
        transformRequest: [data => JSON.stringify(data)] // 参数转换
      });
      // 定义取消函数
      this.serviceToken(service);
      const queryData = params || this.queryData;
      // request拦截器
      service.interceptors.request.use(config => this.interceptors(config));
      service.get(this.exportApi, {
        params: queryData,
        responseType: 'blob',
        cancelToken: source.token
      }).then(res => {
        this.$emit('onComplate', res);
        this.loading = false;
        const headers = res.headers;
        if (headers && headers['content-type'].indexOf('json') !== -1) {
          const a = new Blob([res.data]);
          const reader = new FileReader();
          reader.onload = e => {
            const result = JSON.parse(e.target.result);
            if (result.code === 401) { // 用户过期的情况
              this.loading = false;
              this.$confirm(
                '当前登录已过期，请重新登录',
                '',
                {
                  confirmButtonText: '重新登录',
                  type: 'warning',
                  customClass: 'del-message',
                  iconClass: 'del-icon',
                  showCancelButton: false,
                  center: true
                }
              ).then(() => {
                this.loading = false;
                store.dispatch('FedLogOut').then(() => {
                  location.reload(); // 为了重新实例化vue-router对象 避免bug
                });
              }).catch(() => {
                this.loading = false;
                return;
              });
            } else {
              this.$emit('onErrorExport', result.message);
              this.$message.error(result.message);
            }
          };
          reader.readAsText(a);
        } else {
          this.loading = false;
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const a = document.createElement('a');
          const time = new Date().getTime();
          a.style.display = 'none';
          a.setAttribute('download', `${this.exportName}${standardFormatTime(time)}.xlsx`);
          a.setAttribute('href', url);
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          this.$emit('onSuccessExport', '导出成功');
        }
      }).catch(e => {
        console.error(e);
        this.loading = false;
        const errMsg = typeof e === 'object' ? e.message : e;
        this.$emit('onErrorExport', errMsg || '请求失败');
      });

      this.cancelAxios = source;
    },
    interceptors(config) {
      if (!navigator.onLine) {
        this.$message({
          type: 'warning',
          message: '网络错误！请检查网络状态...'
        });
      }
      return config;
    },
    cancelHttp(msg = '请求已取消') {
      if (this.cancelAxios) {
        this.cancelAxios.cancel(msg);
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.report-export {
  height:32px;
  background:rgba(239,243,251,1);
  border-radius:4px;
  padding: 0;
  font-size:14px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  line-height:32px;
  padding: 0 16px;
  img {
    position: relative;
    top: 2px;
    width: 16px;
    height: 16px;
    margin-left: 10px;
  }
}
</style>
